﻿using System;
using System.Configuration;
using System.Web;
using System.Web.Security;
using Microsoft.VisualBasic;
using Shuba.Business;

namespace Shuba.Web
{
    public partial class login : basePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Response.Cache.SetNoStore();

            //if (Session["UserID"] != null) Response.Redirect("default.aspx");
            txtPassword.Attributes.Add("autocomplete", "off");
            if (ConfigurationManager.AppSettings["admin1.name"] == "" || ConfigurationManager.AppSettings["admin2.name"] == "")
            {
                AlertAndRedirect("Please complete the setup parameters before using the application", "appsetup/setup.aspx");
            }
            else
            {
                this.Form.DefaultFocus = txtUserName.ClientID;
                this.form1.DefaultButton = btnSubmit.UniqueID;
            }
        }

        protected string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipAddress))
            {
                string[] addresses = ipAddress.Split(',');
                if (addresses.Length != 0)
                {
                    return addresses[0];
                }
            }

            return context.Request.ServerVariables["REMOTE_ADDR"];
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string msg = "";
            int LoginPeriod;

            string UserData = "";
            string AppCode = ConfigurationManager.AppSettings["app.code"];
            string RemoteAddr = Request.UserHostAddress.ToString();
            string nip = txtUserName.Text.Trim().ToUpper();

            string returnUrl = Request.QueryString["ReturnUrl"];
            if (returnUrl == null) returnUrl = "default.aspx";

            //Lock login jika dalam periode tertentu melakukan kesalahan
            if (!LoginAttemptManager.userAbleToLogin(GetIPAddress(), this))
            {
                Alert(this.GetGlobalResourceObject("Messages", "UserTryToLogin").ToString());
                return;
            }
            bool IsLDAPUSer = CheckLDAPUser(nip, txtPassword.Text);

            if (IsLDAPUSer)
            {
                bool isRedirect = true;
                FormsAuthentication.Initialize();
                Authentication auth = new Authentication();

                try
                {
                    int isLoginValid = auth.ValidateUser(nip, AppCode);

                    if (isLoginValid == 1 || isLoginValid == 2)
                    {
                        //start get time out 
                        AppParam Appparam = new AppParam();
                        Shuba.Model.AppParamInfo appParamInfo = Appparam.Get();
                        Int16 timeOut = appParamInfo.TIME_OUT;
                        Int16 refreshTime = appParamInfo.REFRESH_TIME;
                        //Int16 warningAD = appParamInfo.WARNING_AD;
                        ProcessDate = appParamInfo.PROCESS_DATE;

                        User user = new User();
                        Shuba.Model.UserInfo info = user.GetLoginInfo(nip, AppCode);

                        DateTime LastLoginDate = info.LoginDate;

                        LoginPeriod = Appparam.GetDateDb().Subtract(LastLoginDate).Minutes; //DateAndTime.DateDiff("n", LastLoginDate, Appparam.GetDateDb(), Microsoft.VisualBasic.FirstDayOfWeek.Sunday, FirstWeekOfYear.Jan1);

                        //if ((info.IsLogin == false) || (info.IsLogin == true && LoginPeriod >= refreshTime))
                        if ((info.IsLogin == false) || (Session["UserID"] == null && info.AppId == AppCode && info.IsLogin == true && RemoteAddr == info.LoginAddr && LoginPeriod >= refreshTime) || (info.IsLogin == true && RemoteAddr != info.LoginAddr && LoginPeriod >= timeOut))
                        {
                            UserData = info.Id + "~" + nip + "~" + info.Name;

                            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, nip, DateTime.Now, DateTime.Now.AddMinutes(timeOut), true, UserData);
                            string hash = FormsAuthentication.Encrypt(ticket);
                            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
                            Response.Cookies.Add(cookie);

                            info.IsLogin = true;
                            info.AppId = AppCode;
                            info.LoginAddr = RemoteAddr;
                            info.LoginDate = Appparam.GetDateDb();

                            Session["UserID"] = info.Id;
                            Session["UnitID"] = info.BranchId; //Untuk Trace File -> Open New Window, check default0.aspx

                            //untuk message jika user akan expired
                            long daysLeft = CheckExpired(txtUserName.Text, txtPassword.Text);
                            if (daysLeft > 0 && daysLeft <= 7)
                            {
                                AlertConfirmation("Password NT Anda akan kadaluarsa dalam [ " + daysLeft + " ] hari\\nApakah Anda akan mengganti password NT sekarang ?", "reset_pwd.aspx");
                                isRedirect = false;
                            }
                            else if (daysLeft < 0)
                            {
                                daysLeft = daysLeft * -1;
                                AlertAndRedirect("Password NT Anda telah kadaluarsa selama [ " + daysLeft + " ] hari\\nSilakan ganti password NT Anda", "reset_pwd.aspx");
                                isRedirect = false;
                            }

                            if (isRedirect)
                            {
                                user.Update(info);
                                AddLog("Login", String.Format("Login To {0} Application, User Name : {1}, Remote Address: {2}", AppCode, txtUserName.Text, RemoteAddr));

                                Response.Redirect(returnUrl);
                            }
                        }
                        else
                        {
                            int minuteleft = refreshTime - LoginPeriod;

                            msg = "Can not logon To Application, this user is already login or not logout properly";
                            if (minuteleft > 0) msg += "\\nPlease wait another " + minuteleft + " minutes to re-login";
                            msg += "\\nLast Login Recorded from [" + RemoteAddr + "] on " + LastLoginDate.ToString("dd MMM yyyy hh:mm:ss tt");
                            Alert(msg);
                        }
                    }
                    else if (isLoginValid == 3)
                    {
                        msg = "Login Failed...!\\nYou and your Alternate doesn\\'t have privilege to access this Application";
                        Alert(msg);
                    }
                    else if (isLoginValid == 4 || isLoginValid == 5 || isLoginValid == 6)
                    {
                        msg = "Login Failed...!\\nYou can\\'t login to this Application\\nThere is an active user (alternate) as your position";
                        Alert(msg);
                    }
                    else if (isLoginValid == 7)
                    {
                        //LoginAttemptManager.userLoginFailed(GetIPAddress());
                        msg = "Login Failed...!\\nYou don\\'t have right to enter this Application";
                        Alert(msg);
                    }
                    else
                    {
                        //LoginAttemptManager.userLoginFailed(GetIPAddress());
                        msg = this.GetGlobalResourceObject("Messages", "UserNotinDB").ToString();
                        Alert(msg);
                    }
                }
                catch (Exception ex)
                {
                    //Alert("The application can not connect to Database Server\\n\\n" + exp.Message.Replace("'","") + "\\n\\nPlease contact your Administrator");
                    //LoginAttemptManager.userLoginFailed(GetIPAddress());
                    Alert("The application can not connect to Database Server\\n\\nPlease contact your Administrator");
                }
            }
            else
            {
                //LoginAttemptManager.userLoginFailed(GetIPAddress());
                msg = this.GetGlobalResourceObject("Messages", "FailedLoginToLDAP").ToString();
                Alert(msg);
            }
        }
    }
}